package com.xing.asm.jtrace;

import com.xing.asm.simple.AsmSimple;
import com.xing.asm.simple.MyClassLoader;
import org.objectweb.asm.*;

import java.io.FileOutputStream;

public class AdivceMain {

    public static void main(String[] args) throws Exception{

        final Class<?> advisorClass = Thread.currentThread().getContextClassLoader().loadClass("com.xing.asm.jtrace.Advisor");

        // 初始化AdvisorInvoker
        AdvisorInvoker.init(
                advisorClass.getMethod("onMethodBegin",
                        Class.class,
                        Object.class,
                        String.class,
                        String.class,
                        Object[].class));


        ClassReader cr = new ClassReader(AsmSimple.class.getName());
        ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS);
        ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
            @Override
            public MethodVisitor visitMethod(int access, final String name, final String desc, String signature, String[] exceptions) {
                MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);
                return new MethodAdvisorWriter(AdviceInvoker.class.getName(), mv, access, name, desc);
            }
        };
        cr.accept(cv, ClassReader.EXPAND_FRAMES);

        byte[] code = cw.toByteArray();

        FileOutputStream fos = new FileOutputStream("E:\\ljx\\asm\\AsmAdviceSimple.class");
        fos.write(code);
        fos.close();


//        MyClassLoader myClassLoader = new MyClassLoader();
//        Class asmSimpleClass = myClassLoader.defineClass(AsmSimple.class.getName(), code);
//        java.lang.reflect.Method method = asmSimpleClass.getMethod("excute", null);
//        Object asmSimpleInstance = asmSimpleClass.newInstance();
//        method.invoke(asmSimpleInstance, null);

    }
}
